const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');

// 确保scripts目录存在
if (!fs.existsSync('scripts')) {
  fs.mkdirSync('scripts');
}

// 确保dist目录存在
if (!fs.existsSync('dist')) {
  fs.mkdirSync('dist');
}

// 复制必要的文件到dist目录
const filesToCopy = [
  'package.json',
  'package-lock.json',
  '.env.production',
  'app.js',
];

filesToCopy.forEach(file => {
  if (fs.existsSync(file)) {
    fs.copyFileSync(file, path.join('dist', file));
  }
});

// 复制src目录
function copyDir(src, dest) {
  if (!fs.existsSync(dest)) {
    fs.mkdirSync(dest, { recursive: true });
  }

  const entries = fs.readdirSync(src, { withFileTypes: true });

  for (const entry of entries) {
    const srcPath = path.join(src, entry.name);
    const destPath = path.join(dest, entry.name);

    if (entry.isDirectory()) {
      copyDir(srcPath, destPath);
    } else {
      fs.copyFileSync(srcPath, destPath);
    }
  }
}

copyDir('src', path.join('dist', 'src'));

// 在dist目录下安装生产依赖
process.chdir('dist');
console.log('Installing production dependencies...');
execSync('npm install --production', { stdio: 'inherit' });

console.log('Build completed successfully!');